package cn.dapeng.linked;

import cn.dapeng.utils.BuilderArray;
import cn.dapeng.utils.LinkedCreator;

import java.util.ArrayList;
import java.util.List;

/**
 * 给一个链表， 和链表中的一个节点信息
 * 返回删除这个节点后 整个链表  返回头部信息
 */
public class DeleteNode {

    public static LinkedNode delete(LinkedNode head, LinkedNode node) {

        if (head == null) {
            return null;
        }

        if (head == node) {
            return head.next;
        }
        LinkedNode cur = head, per;
        while (cur != null && node != null) {
            per = cur;
            cur = head.next;
            if (cur == node) {
                per.next = node.next;
                node = null;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        int testTimes = 10_0000;

        for (int i = 0; i < testTimes; i++) {
            LinkedNode head = LinkedCreator.createLinked(100, 10);

            int size = LinkedCreator.getLength(head);

            int step = (int) (Math.random() * size) > 2 ? 2 : -1;

            LinkedNode current = head, deleteNode = null;
            while (step-- > 0 && current != null) {
                deleteNode = current.next;
            }

            if (deleteNode != null) {
                List<Integer> l1 = toList(head);
                head = delete(head, deleteNode);

                List<Integer> l2 = toList(head);
                remove(l1, deleteNode.value);
                if (!BuilderArray.checkArrayEqual(l1.stream().mapToInt(t -> t).toArray(), l2.stream().mapToInt(t -> t).toArray())) {
                    System.out.println("Oops");
                    break;
                }
            }
        }


    }

    public static List<Integer> toList(LinkedNode head) {
        if (head == null) {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        LinkedNode cur = head;
        while (cur != null) {
            list.add(cur.value);
            cur = cur.next;
        }
        return list;
    }

    public static List<Integer> remove(List<Integer> list, Integer num) {
        for (Integer i : list) {
            if (i.equals(num)) {
                list.remove(i);
                break;
            }
        }
        return list;
    }
}
